import json

from fastapi import Request, APIRouter


from core.Response import success
from models.models import Post
from schemas.posts import serialize_posts

router = APIRouter(prefix='')


@router.get("/{id}", )
async def get_posts(request: Request, id: int):
    print("get_posts" * 10, id)
    print()
    posts=await request.app.state.cache.get('posts')
    print(posts)
    queryset = await Post.get_or_none(id=id)  # 假设你使用的是Tortoise ORM

    return {
        "code": 0,
        "data": posts,
    }


@router.post("", response_model=dict)
async def create_post(request: Request):
    # 尝试从缓存中获取数据
    cached_posts = await request.app.state.cache.get('posts')
    if cached_posts:
        print("从缓存中获取数据")
        return success(data=json.loads(cached_posts))

    print("从数据库中获取数据")
    # 获取前12条随机数据
    # recent_posts_queryset = await Post.all().order_by('id').limit(12)
    # recent_posts = await serialize_posts(recent_posts_queryset)

    # 获取is_slider为True的数据
    slider_posts_queryset = await Post.filter(is_slider=True)
    slider_posts = await serialize_posts(slider_posts_queryset)

    # 获取isTop为True的数据
    top_posts_queryset = await Post.filter(isTop=True)
    top_posts = await serialize_posts(top_posts_queryset)

    # 将 Pydantic 模型转换为字典
    # recent_posts_dict = [post.dict() for post in recent_posts]
    slider_posts_dict = [post.dict() for post in slider_posts]
    top_posts_dict = [post.dict() for post in top_posts]

    response_data = {
        # 'row_count': recent_posts_dict,
        'slider_posts': slider_posts_dict,
        'top_posts': top_posts_dict,
    }
    print(response_data)

    # 将数据序列化为 JSON 字符串并存入缓存
    await request.app.state.cache.set('posts', json.dumps(response_data, default=str),ex=259200)

    return success(data=response_data)

